# -- encoding: utf-8 --
#!/usr/bin/env python

# Copyright 2010 István Szentandrási
# <etude-music-player@googlegroups.com>

# This file is part of Etude.
#
# Etude is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as 
# published by the Free Software Foundation, either version 3 
# of the License, or (at your option) any later version.
#
# Etude is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Etude. If not, see <http://www.gnu.org/licenses/>.

import gtk
import os
from client.common import PB_PAUSE, PB_PLAY, PB_STOP
from main import CONFIG_DIR

class Actions(object):

    def __init__(self, control):

        uimanager = control.uimanager
        self.uimanager = uimanager
        self.load()

        guiactions = [
                ('toggle_main', None, _("Show/Hide Main Window"), '<Ctrl>h', None,
                    lambda x: control.layout.toggle_main()),
                ('preferences', gtk.STOCK_PREFERENCES, None, 'F5', None,
                    lambda widget: control.show_preferences()),
                ('stop_daemon', gtk.STOCK_QUIT, _('Stop daemon and quit'), '', None,
                    lambda widget: control.quit(force_daemon_stop=True)),
                ('quit', gtk.STOCK_QUIT, None, '<Ctrl>q', None,
                    lambda widget: control.quit()),
                ('about', gtk.STOCK_ABOUT, None, None, None,
                    lambda widget: control.show_about())
                ]

        clientactions = [
                ('prev', gtk.STOCK_MEDIA_PREVIOUS, None, '<Ctrl>Left', None,
                    lambda x: control.client.playback.prev()),
                ('play', gtk.STOCK_MEDIA_PLAY, None, None, None,
                    lambda x: control.client.playback.start()),
                ('pause', gtk.STOCK_MEDIA_PAUSE, None, None, None,
                    lambda x: control.client.playback.pause()),
                ('playpause', None, _("Play/Pause"), '<Ctrl>p', None,
                    lambda x: control.client.playback.toggle()),
                ('stop', gtk.STOCK_MEDIA_STOP, None, '<Ctrl>s', None,
                    lambda x: control.client.playback.stop()),
                ('next', gtk.STOCK_MEDIA_NEXT, None, '<Ctrl>Right', None,
                    lambda x: control.client.playback.next()),
                ('lower', None, _("Lower Volume"), '<Ctrl>KP_Add', None,
                    lambda x: control.client.playback.volume_set_relative(diff=3, fast=True)),
                ('raise', None, _("Raise Volume"), '<Ctrl>KP_Subtract', None,
                    lambda x: control.client.playback.volume_set_relative(diff=-3, fast=True)),
                ('repeat', None, _("_Repeat"), '<Ctrl>r', _("Repeat song/Repeat_all"),
                    lambda x: control.client.playlist.set_repeat()),
                ('shuffle', None, _("Shu_ffle"), '<Ctrl>f', _("Shuffle the playlist"),
                    lambda x: control.client.playlist.shuffle()),
                ('clear', gtk.STOCK_CLEAR, _("_Clear"), '<Ctrl>Delete', None,
                    lambda x: control.client.playlist.clear())
                ]

        actiongroup = gtk.ActionGroup("Main shortcuts")
        actiongroup.add_actions(guiactions)
        actiongroup.add_actions(clientactions)
        uimanager.insert_action_group(actiongroup, 0)
        #set the stop daemon action visible or not in the menu
        if control.profile['stop_daemon']:
            action = actiongroup.get_action("stop_daemon")
            action.set_visible(False)
            action.set_sensitive(False)
        strs = ["<accelerator action=\""+action[0]+"\" name=\"acc_"+action[0]+"\" />" for action in guiactions+clientactions]
        control.uimanager.add_ui_from_string("<ui>"+"".join(strs)+"</ui>")
        
        self.new_status(control.client, control.client.playback.status)
        control.client.connect("e_playback_status", self.new_status)

    def new_status(self, client, status=-1):
        pause = self.get_action("pause")
        play = self.get_action("play")
        if status == PB_PLAY:
            pause.set_visible(True)
            play.set_visible(False)
        else:
            pause.set_visible(False)
            play.set_visible(True)
    
    def save(self):
        gtk.accel_map_save(os.path.join(CONFIG_DIR, 'shortcuts'))

    def load(self):
        gtk.accel_map_load(os.path.join(CONFIG_DIR, 'shortcuts'))
    
    def __del__(self):
        self.save()

    def get_action(self, name):
        """
        groups = self.uimanager.get_action_groups()
        acts = [group.get_action(name) for group in groups]
        acts = [act for act in acts if act is not None]
        try:
            return acts[0]
        except IndexError:
            return None
        """
        return self.uimanager.get_action("/acc_"+name)
    
    def change_accel(self, accel_path, key_string, dialog_parent=None):
        keyval,mods = gtk.accelerator_parse(key_string)
        err_msg = ""
        if gtk.accelerator_valid(keyval, mods) or len(key_string.strip()) == 0:
            result = gtk.accel_map_change_entry(accel_path, keyval, mods, False)
            if result or (keyval==0 and mods == 0):
                pass
            else:
                err_msg = _("Shortcut may already exist for other action.")
        else:
            err_msg = _("Wrong format.")
        if err_msg:
            dd = gtk.MessageDialog(dialog_parent, 
                    flags=gtk.DIALOG_DESTROY_WITH_PARENT|gtk.DIALOG_MODAL,
                    type=gtk.MESSAGE_ERROR,
                    buttons=gtk.BUTTONS_OK)
            dd.set_markup(_("Unable to set shortcut.") + "\n" +err_msg)
            dd.run()
            dd.destroy()
            return False
        return True


